﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Nxg.Blog.Core.Documents;

namespace Nxg.Blog.Core {

    public class SpamShield {
        [Required]
        public int Tick { get; set; }

        [Required]
        public string Hash { get; set; }
    }
    public interface ISpamShieldService {
        int CreateTick (string key);

        string GenerateHash (int tick);

        bool IsSpam (SpamShield command);
    }
    public class SpamShieldService : ISpamShieldService {
        private readonly DataContext _context;

        public SpamShieldService (DataContext context) {
            _context = context;
        }

        public int CreateTick (string key) {
            var spamHash = new SpamHash {
                PostKey = key,
                CreatedTime = DateTime.Now,
                Hash = string.Empty
            };
            _context.SpanHash.Add (spamHash);
            _context.SaveChanges ();
            return spamHash.Id;
        }

        public string GenerateHash (int tick) {
            var nonhash = string.Empty;

            var spamHash = _context.SpanHash.SingleOrDefault (x => x.Id == tick);

            if (spamHash == null || spamHash.Pass || !spamHash.Hash.IsNullOrWhitespace ())
                return nonhash;

            spamHash.Hash = new Random ().NextDouble ().ToString ();
            _context.SaveChanges ();
            return spamHash.Hash;
        }

        public bool IsSpam (SpamShield command) {
            if (command.Hash.IsNullOrWhitespace ())
                return true;

            var spamHash = _context.SpanHash.FirstOrDefault (x => x.Id == command.Tick);

            if (spamHash == null || spamHash.Pass || spamHash.Hash != command.Hash)
                return true;

            spamHash.Pass = true;
            _context.SaveChanges ();
            return false;
        }
    }
}